$(function(){
    if($.fn.fancybox)
        $('.fancy').fancybox();


    adminCategoryFilters.init();
    adminGoodsFilters.init();
    adminGoodsParser.init();
    adminInitEditor();
    adminOrder.init();
    adminNewGoodsView.init();
});

var adminInitEditor = function() {
    if(window['tinyMCE'])
    {
        tinyMCE.init({
            // General options
            language : $('input#tinymcelang').val(),
            mode : "textareas",
            theme : "advanced",
            plugins : "autolink,lists,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",

            width : '440',
            height : '340',

            editor_selector : "editor",

            // Theme options
            theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect",
    //        theme_advanced_buttons2 : "fontselect,fontsizeselect,|,pasteword,|,bullist,numlist,|,outdent,indent,blockquote",
            theme_advanced_buttons2 : "pasteword,|,bullist,numlist,|,outdent,indent,blockquote",
            theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup",
            theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage",
            theme_advanced_buttons5 : "charmap,emotions,iespell,media,advhr,|,forecolor,backcolor,|,link,unlink,anchor,image,cleanup,code",
            theme_advanced_toolbar_location : "top",
            theme_advanced_toolbar_align : "left",
            theme_advanced_statusbar_location : "bottom",
            theme_advanced_resizing : true,

            // Skin options
            skin : "o2k7",
            skin_variant : "silver",
            relative_urls : false,
            convert_urls : false,
            remove_script_host : false,

            // Drop lists for link/image/media/template dialogs
            template_external_list_url : "js/template_list.js",
            external_link_list_url : "js/link_list.js",
            external_image_list_url : "js/image_list.js",
            media_external_list_url : "js/media_list.js"

        });
    }
}

var adminNewGoodsView = {
    init: function(){
        $('.urls .add').on('click', function(e){
            e.preventDefault();

            var obj = $(this);

            AjaxLoader.show(obj.parent());
            $.post($(this).attr('href'), {'add': 1}, function(response){
                AjaxLoader.hide();
                if(response && response.html)
                {
                    obj.before($(response.html));
                }
            }, 'json');
        });

        $('.urls .not-new').on('click', function(e){
            e.preventDefault();

            var obj = $(this);
            AjaxLoader.show(obj.parent());
            $.post($(this).attr('href'), {'is_not_new': 1}, function(response){
                AjaxLoader.hide();
                if(response && response.html)
                {
                    obj.before($(response.html));
                }
            }, 'json');
        });
    }
};

var adminCategoryFilters = {
    init : function(){
        var inpt = $('.admin.category.filters .item.template input');

        inpt.on('blur', function(){
            console.log($(this).val());
            if($(this).val() != '')
            {
                var lastInput = $('.admin.category.filters .item.template input').last();
                var templ = $('.admin.category.filters .template');
                var clone = templ.clone(true);

                clone.find('input').val('');
                templ.after(clone);

                templ.removeClass('template');
                templ.off('blur');

                $('.admin.category.filters .item.template input').last().focus();
            }
        });

        $('.admin.category.filters form').on('submit', function(e){

            var allow = true;

            $('.admin.category.filters .item.template').each(function(){
                if($(this).find('input').val() != '')
                    allow = false;
            });

            if(!allow)
                e.preventDefault();

        });

    }
};

var adminGoodsFilters = {
    init : function(){

        $('.admin.edit.goods select[name="category_id"]').on('change', function(e){
            var categoryId = $(this).val();

            $.get('/admin/goods/properties/categoryId/' + categoryId, {}, function(response){
                $('#properties-wrapper').html(response);
            });
        });

    }
};

var adminGoodsParser = {
    init: function(){
        $('.admin.edit.goods select[name="parser_id"]').on('change', function(e){
            adminGoodsParser.loadSizes($(this));
        });

        adminGoodsParser.loadSizes($('.admin.edit.goods select[name="parser_id"]'));

        $('.admin.edit.goods input[name="original_url"]').on('change', function(e){
            adminGoodsParser.setFrame($(this).val());
        });

        adminGoodsParser.setFrame($('.admin.edit.goods input[name="original_url"]').val());
    },

    setFrame: function(val){
//        $('#frame').html($('<iframe src="/admin/goods/loadframe?url='+ val +'"/>'));
    },

    loadSizes : function(th) {
        var request = {
            'url' : $('.admin.edit.goods input[name="original_url"]').val(),
            'parser_id' : $(th).val()
        }

        if(request.parser_id > 0 && request.url != '')
        {
            $.post('/admin/goods/parser', request, function(response){
                if(response)
                {
                    if(response.sizes_name)
                    {
                        $('.admin.edit.goods .property-item.type-3 .value-item').each(function(){
                            var name = $(this).find('input').attr('name');
                            var stockId = $(this).find('input').attr('rel');

                            var re = /property_value\[\d+\]\[(\d+)\]/i;
                            var found = name.match(re);

                            console.log();

                            var select = $('<select/>').attr('name', 'property_size_id['+ found[1] +']');

                            select.append($('<option value="">---------------------</option>'));
                            for(var i in response.sizes_name)
                            {
                                select.append($('<option '+ (i==stockId ? 'selected=""' : '') +' value="'+ i +'['+ response.sizes[i] +']">'+ response.sizes_name[i] +'</option>'));
                            }

                            $(this).append(select);
                        })

                    }
                }
            }, 'json');
        }
    }
};

var adminOrder = {
    init: function() {
        $('#select-status').on('change', function(e){
            window.location.href = $(this).val();
        });
    }
};

var AjaxLoader = {
    show : function( obj, text )
    {
        text = text || '';
        obj = $(obj);

        var _loader = AjaxLoader._setLayers( obj, text );

        $('body div:first').after(_loader);
    },
    _setLayers : function( obj, text )
    {
        $(obj).each(function(){

            var _position = $(this).position();

            var _box = $('<div />', {
                'class' : 'ajax-loader'+ (text != '' ? ' text' : '')
            }).css({
                    'width' : $(this).innerWidth(),
                    'height' : $(this).innerHeight(),
                    'left'	: 0,
                    'top'	: 0
                });

            if(text != '')
            {
                _box.append($('<p>'+ text +'</p>'));
            }

            _box.append($('<img />', {
                'src' : ''
            }));

            $(this).css({
                'position': 'relative'
            }).append( _box );
        });
    },
    hide : function()
    {
        $('.ajax-loader').hide(1).remove();
    }
};